package com.gph.saviorframework.security.web.editor;

import com.gph.saviorframework.common.model.User;
import com.gph.saviorframework.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.beans.PropertyEditorSupport;

/**
 * Created by guopeihui on 2016/11/4.
 */
public class UserEditor extends PropertyEditorSupport {

    @Autowired
    private UserService userService;

    public UserEditor(UserService userService){
        this.userService = userService;
    }

    /**
     * @return
     * @see PropertyEditorSupport#getAsText()
     */
    @Override
    public String getAsText() {
        if (getValue() instanceof User) {
            return ((User) getValue()).getUsername().toString();
        }
        return null;
    }

    /**
     * @param text
     * @throws IllegalArgumentException
     * @see PropertyEditorSupport#setAsText(String)
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Object user = userService.get(text);
        if (user != null) {
            setValue(user);
        } else {
            setValue(new User(text));
        }
    }
}
